package algo3.display;

import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.Transparency;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.net.URL;
import javax.imageio.ImageIO;

public class Imagen extends Canvas {
	private static final long serialVersionUID = 1L;
	
	/*ATRIBUTOS*/
	private int pivoteX;
	private int pivoteY;
	private int posX;
	private int posY;
	private int ancho;
	private int alto;
	private double rotacion;	
	private BufferedImage img;
	
	/*GETTERS Y SETTERS*/
	public int getAncho()  { 
		return ancho; 
	}
	
	public int getAlto()  { 
		return alto; 
	}
	
	public int getPosX()  { 
		return posX; 
	}
	
	public void setPosX(int i) {	
		posX = i; 
	}

	public int getPosY() {
		return posY; 
	}
	
	public void setPosY(int i) { 
		posY = i; 
	}
	
	public double getRotacion() {
		return rotacion; 
	}
	
	public void setRotacion(double i) { 
		rotacion = i; 
	}
	
	
	public int getPivoteX()  { 
		return pivoteX; 
	}
	
	public void setPivoteX(int i) {	
		pivoteX = i; 
	}

	public int getPivoteY() {
		return pivoteY; 
	}
	
	public void setPivoteY(int i) { 
		pivoteY = i; 
	}

	/*CONSTRUCTOR*/
	public Imagen(String path){
		

		posX = 0;
		posY = 0;
		pivoteX = 0;
		pivoteY = 0;
		rotacion = 0;
		
		img = cargarImagenCompatible(path);
		
		
	}
	
	/*METODOS PUBLICOS*/
	public void dibujar (Graphics2D grafico){
		int pivX = posX + pivoteX;
		int pivY = posY + pivoteY;
		//Rotacion y posicion de la imagen
		grafico.translate(-pivoteX, -pivoteY);
		grafico.rotate(rotacion, pivX, pivY);
		
		grafico.drawImage(img, posX, posY, this);
		
		grafico.rotate(-rotacion, pivX, pivY);
		grafico.translate(pivoteX, pivoteY);
		
	}
	
	
	/*METODOS PRIVADOS*/
	
	private BufferedImage cargarImagenCompatible(String name) {
		BufferedImage loaded = (BufferedImage)cargarImagen(name);
		BufferedImage compatible = crearImagenCompatible(loaded.getWidth(),loaded.getHeight(),Transparency.BITMASK); 
		Graphics g = compatible.getGraphics();
		g.drawImage(loaded,0,0,this);
		return compatible;
	}
	
	private BufferedImage cargarImagen(String nombre) {
		URL url=null;
		try {
			url = getClass().getClassLoader().getResource(nombre);
			return ImageIO.read(url);
		} catch (Exception e) {
			System.out.println("Error al cargar la imagen de "+url);
			System.exit(0);
			return null;
		}
	}	

	private BufferedImage crearImagenCompatible(int ancho, int alto, int transparencia) {
		this.alto = alto;
		this.ancho = ancho;
		
		GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
		BufferedImage compatible = gc.createCompatibleImage(ancho, alto, transparencia);
		return compatible;
	}

}
